package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderTo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderCreateListener {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private OrderService orderService;
    @RabbitHandler
    public void handleOrderCreate(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        //订单超时过后，自动修改订单状态为取消
        //查询订单最新状态
        OrderEntity order = orderService.getById(orderEntity.getId());
        if(order!=null){
            //判断订单状态
            if(order.getStatus()== OrderStatusEnum.CREATE_NEW.getCode()){
                //如果还没付款，则取消订单
                OrderEntity update = new OrderEntity();
                update.setId(orderEntity.getId());
                update.setStatus(OrderStatusEnum.CANCLED.getCode());
                orderService.updateById(update);

                //订单取消后主动给库存系统发送消息,防止由于订单系统故障导致解锁失败
                OrderTo orderTo = new OrderTo();
                BeanUtils.copyProperties(update,orderTo);
                orderTo.setOrderSn(order.getOrderSn());
                rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",orderTo);

                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }else {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }else{
            //订单不存在
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
}
